import React, { useState, useEffect } from 'react'
import './index.css'
import Search from '../../components/Search'
import { useNavigate, useLocation, Link } from 'react-router-dom';
import { Pagination } from 'antd';
import axios from 'axios';
import '../../static/axios_url'
import { message } from 'antd';
import { Breadcrumb } from 'antd'

export default function Classify() {
    const loc = useLocation()
    //请求回来的数据初始化
    const [count, setcount] = useState({})
    //排序数据初始化
    const [countsort, setcountsort] = useState({})
  

    useEffect(() => {
        var bid = decodeURIComponent(loc.search.split('?')[1])
        const arr = bid.split('=')
        if (loc.search === '') {
            axios.post('http://localhost:3001/search').then((res) => {
                setcount({
                    place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                    kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                    information: res.data
                })
            })
            axios.post('http://localhost:3001/search', { ye: 1 }).then((res) => {
                setcountsort({
                    place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                    kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                    information: res.data
                })
            })
        } else if (arr[0] === 'type') {
            //    console.log(arr[1]);
            axios.post('http://localhost:3001/search', { type: arr[1] * 1 }).then((res) => {
                setcount({
                    place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                    kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                    information: [...res.data, ...res.data]
                })
                setcountsort({
                    place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                    kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                    information: [...res.data, ...res.data]
                })
            })
        } else {
            axios.post('http://localhost:3001/search', { good: bid }).then((res) => {
                if (res.data.length===0) {
                    navigate('/tosearchempty')

                }else{
                    setcount({
                        place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                        kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                        information: [...res.data, ...res.data]
                    })
                    setcountsort({
                        place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                        kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                        information: [...res.data, ...res.data]
                    })
                }          
            })
        }
    }, [loc.search.split('?')[1]])
    console.log(count);
    useEffect(() => {
        document.getElementsByClassName('foodLisBtn')[0].getElementsByTagName('span')[0].className = 'check'
        setcountarr({
            countarr: false,
            nextday: false,
            kmg: [
                { mg: 500, ischeck: false },
                { mg: 1000, ischeck: false },
                { mg: 1500, ischeck: false },
                { mg: 2000, ischeck: false }
            ]
        })
    }, [])
    function lxCheck(num) {
        return () => {
            let span = document.getElementsByClassName('foodLisBtn')[0].getElementsByTagName('span')
            for (let i = 0; i < span.length; i++) {
                span[i].className = ''
            }
            span[num].className = 'check'
            //销量排序
            if (num === 0) {
                const sortup = { ...count }
                sortup.information.sort((a, b) => {
                    return a.xiao_liang - b.xiao_liang
                })
                setcountsort(sortup)
            }
            //评价排序
            if (num === 2) {
                const sortup = { ...count }
                sortup.information.sort((a, b) => {
                    return a.ping_jia - b.ping_jia
                })
                setcountsort(sortup)
            }
        }
    }
    function updown() {
        return () => {
            setupOrdown(!upOrdown)
        }
    }
    const [upOrdown, setupOrdown] = useState(true)
    //全国\次日达按钮点击变色和选择加入购物车规格变色
    const [countarr, setcountarr] = useState({
        countarr: '',
        nextday: '',
        kmg: [],
    })

    function changecolor() {
        const changecolor = JSON.parse(JSON.stringify(countarr))
        changecolor.countarr = !changecolor.countarr
        setcountarr(changecolor)
    }
    function changecolor2() {
        const changecolor2 = JSON.parse(JSON.stringify(countarr))
        changecolor2.nextday = !changecolor2.nextday
        setcountarr(changecolor2)
    }
    //价格排序
    function sortfition() {
        const sortup = { ...count }
        if (upOrdown === false) {
            sortup.information.sort((a, b) => {
                return b.new_price - a.new_price
            })
            setcountsort(sortup)
        } else {
            sortup.information.sort((a, b) => {
                return a.new_price - b.new_price
            })
            setcountsort(sortup)
        }
    }
    //点击改变选择规格的边框和背景
    function ischocemg(i) {
        const ischoceit = JSON.parse(JSON.stringify(countarr))
        for (let index = 0; index < ischoceit.kmg.length; index++) {
            ischoceit.kmg[index].ischeck = false
        }
        ischoceit.kmg[i].ischeck = !ischoceit.kmg[i].ischeck
        setcountarr(ischoceit)
    }



    //点击跳转详情页
    const navigate = useNavigate()
    function lookCommodity(num) {
        return () => {
            navigate('/tocar?' + num)
        }
    }
    //点击购物车小图标的按钮弹出加入购物车的弹窗
    const [ischoceshop, setchoceshop] = useState({ id: '', nowprice: '', oldprice: '' })
    function addcar(id, nowprice, oldprice) {
        const carwindow = document.getElementsByClassName('C-modul')[0]
        carwindow.className = 'C-modulshow'
        setchoceshop({ id: id, nowprice: nowprice, oldprice: oldprice })
    }
    //点击弹窗的加入购物车的按钮
    function addtocar() {
        setaddcar(0)
        const a = countarr.kmg.filter(v => {
            return v.ischeck === true
        })
        if (countaddcar === 0) {
            message.success('请选择数量');
        } else {
            const addshop = { g_id: ischoceshop.id, u_id: '1', g_num: countaddcar, g_g: a[0].mg }
            console.log(addshop);
            const modul = document.getElementsByClassName('C-modulshow')[0]
            modul.className = 'C-modul'
            axios.post('http://localhost:3001/addShopcar', { g_id: ischoceshop.id, u_id: '1', g_num: countaddcar, g_g: a[0].mg }).then((res) => {
                console.log(res);
            })
        }
    }
    //点击加号购物车-1
    //购物车初始化
    const [countaddcar, setaddcar] = useState(0)
    function loseone() {
        if (countaddcar > 0) {
            setaddcar(countaddcar - 1)
        } else {
            setaddcar(0)
        }
    }
    function nowpage(current) {
        console.log(current);
        axios.post('http://localhost:3001/search', { ye: current }).then((res) => {
            setcountsort({
                place: ['河南省', '陕西省', '河南省', '陕西省', '河南省', '陕西省'],
                kind: ['红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果', '红富士苹果', '洛川苹果'],
                information: res.data
            })
        })
    }
    return (
        <div>
            <Search></Search>
            <hr />
            <div className="P-top">
                <Breadcrumb>
                    <Breadcrumb.Item>您的当前位置</Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <Link to='/'>首页</Link>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <Link to='/tosearch'>全部商品</Link>
                    </Breadcrumb.Item>

                </Breadcrumb>
                {/* <ul>
                    <li>您的当前位置:</li>
                    <li>首页&nbsp;<i className='fa fa-angle-right'></i></li>
                    <li>全部商品&nbsp;<i className='fa fa-angle-right'></i></li>
                    <li>苹果&nbsp;<i className='fa fa-angle-right'></i></li>
                    <li>阿苏克</li>
                </ul> */}
            </div>
            <div className="C-middle">
                <div className='foodLisBtn'>
                    <span className="btn" onClick={lxCheck(0)}>销量</span>
                    <span className="btn" onClick={sortfition} onMouseUp={lxCheck(1)} onMouseDown={updown()}><strong>价格</strong> <i className="fa fa-caret-up up" id={!upOrdown ? '' : 'anthis'}></i><i className="fa fa-caret-down down" id={upOrdown ? '' : 'anthis'}></i></span>
                    <span className="btn" onClick={lxCheck(2)}>评价最高</span>
                    <div className="C-screen">
                        <strong>筛选:</strong>
                        <span className={countarr.countarr ? 'C-green' : 'C-gray'} onClick={changecolor}>全国</span>
                        <span className={countarr.nextday ? 'C-green' : 'C-gray'} onClick={changecolor2}>次日达</span>
                    </div>
                </div>

                <ul className="homeLi-main">
                    {
                        countsort?.information?.map((homeData, i) => {
                            return (
                                <li key={i}>
                                    <img src={homeData.img} alt="" />
                                    <h3 onClick={lookCommodity(homeData.id)}>{homeData.title}</h3>
                                    <h4>{homeData.tip}</h4>
                                    <span className="new_price">￥{homeData.new_price}</span><span className="old_price">￥{homeData.old_price}</span><i className="fa fa-shopping-cart" onClick={() => addcar(homeData.s_id, homeData.new_price, homeData.old_price)}></i>
                                </li>
                            )
                        })
                    }
                </ul>
            </div>
            <div className="peges">
                <Pagination onChange={nowpage} showQuickJumper defaultCurrent={1} total={count?.information?.length} pageSize={12} />
            </div>
            <div className="C-modul">
                <h4>请选择产品规格</h4>
                <hr />
                <div className="nowprice">
                    <strong>现价：￥{ischoceshop.nowprice}</strong>&nbsp;&nbsp;&nbsp;<span>原价：{ischoceshop.oldprice}</span>
                </div>
                <div className="chocekg">
                    <div className="ischocekg">请选择规格</div>
                    {
                        countarr.kmg.map((v, i) => {
                            return (
                                <div className={v.ischeck ? 'kgnum1' : 'kgnum'} onClick={() => ischocemg(i, v.mg)} key={i}>{v.mg}</div>
                            )
                        })
                    }

                    <div className="addchar">
                        <div className="ischocekg">数量:</div>
                        <div className="addnum">
                            <div className="losenum" onClick={loseone}><i className='fa fa-minus'></i></div>
                            <div className="carnums">{countaddcar}</div>
                            <div className="losenum" onClick={() => setaddcar(countaddcar + 1)}><i className='fa fa-plus'></i></div>
                        </div>
                        <div className="to-cart" onClick={addtocar}>
                            添加到购物车
                        </div>

                    </div>

                </div>
            </div>

        </div>
    )
}
